using SqlSugar;
using SqlsugarService.Application.DTOs.QualityInspection;
using SqlsugarService.Application.Until;
using SqlsugarService.Domain.QualityInspection;
using SqlsugarService.Infrastructure.DbContext;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SqlsugarService.Application.Service.QualityInspection
{
    /// <summary>
    /// 质检方案与报工质检关联服务实现类
    /// </summary>
    public class QualityInspectionPlanWorkReportService
    {
        #region 依赖注入

        private readonly SqlSugarDbContext _dbContext;

        public QualityInspectionPlanWorkReportService(SqlSugarDbContext dbContext)
        {
            _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
        }

        #endregion

        #region 质检操作核心方法

        /// <summary>
        /// 质检操作：修改报工质检状态为已质检，并添加质检方案关联
        /// </summary>
        /// <param name="workReportInspectionId">报工质检Id</param>
        /// <param name="qualityInspectionPlanIds">质检方案Id列表</param>
        /// <param name="updatedBy">操作者</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<QualityInspectionOperationResult>> ProcessQualityInspectionAsync(
            Guid workReportInspectionId,
            List<Guid> qualityInspectionPlanIds,
            string? updatedBy = null)
        {
            try
            {
                // 开启事务
                await _dbContext.Db.BeginTranAsync();

                // 1. 修改报工质检状态为已质检
                var updateResult = await _dbContext.Db.Updateable<WorkReportInspectionEntity>()
                    .SetColumns(x => new WorkReportInspectionEntity 
                    { 
                        Status = "已质检",
                        UpdatedBy = updatedBy,
                        UpdatedAt = DateTime.UtcNow
                    })
                    .Where(x => x.Id == workReportInspectionId && !x.IsDeleted)
                    .ExecuteCommandAsync();

                if (updateResult == 0)
                {
                    await _dbContext.Db.RollbackTranAsync();
                    return ApiResult<QualityInspectionOperationResult>.Fail("报工质检记录不存在或已删除", ResultCode.NotFound);
                }

                // 2. 批量添加质检方案关联记录
                var associations = new List<QualityInspectionPlanWorkReportEntity>();
                
                foreach (var planId in qualityInspectionPlanIds)
                {
                    var association = new QualityInspectionPlanWorkReportEntity
                    {
                        Id = Guid.NewGuid(),
                        QualityInspectionPlanId = planId,
                        WorkReportInspectionId = workReportInspectionId,
                        Version = 1,
                        VersionDescription = "质检操作添加",
                        IsCurrentVersion = true,
                        EffectiveTime = DateTime.UtcNow,
                        CreatedBy = updatedBy,
                        CreatedAt = DateTime.UtcNow,
                        UpdatedBy = updatedBy,
                        UpdatedAt = DateTime.UtcNow
                    };

                    associations.Add(association);
                }

                // 批量插入关联记录
                await _dbContext.Db.Insertable(associations).ExecuteCommandAsync();

                // 3. 提交事务
                await _dbContext.Db.CommitTranAsync();

                // 4. 返回结果
                var result = new QualityInspectionOperationResult
                {
                    WorkReportInspectionId = workReportInspectionId,
                    Status = "已质检",
                    ProcessedAt = DateTime.UtcNow,
                    ProcessedBy = updatedBy,
                    AddedAssociationsCount = associations.Count,
                    AssociationIds = associations.Select(x => x.Id).ToList()
                };

                return ApiResult<QualityInspectionOperationResult>.Success(result, ResultCode.Success);
            }
            catch (Exception ex)
            {
                await _dbContext.Db.RollbackTranAsync();
                return ApiResult<QualityInspectionOperationResult>.Fail(
                    $"质检操作失败: {ex.Message}", ResultCode.Error);
            }
        }



        #endregion


    }

    #region 辅助类定义

    /// <summary>
    /// 质检操作结果
    /// </summary>
    public class QualityInspectionOperationResult
    {
        /// <summary>
        /// 报工质检Id
        /// </summary>
        public Guid WorkReportInspectionId { get; set; }

        /// <summary>
        /// 质检状态
        /// </summary>
        public string Status { get; set; } = "已质检";

        /// <summary>
        /// 处理时间
        /// </summary>
        public DateTime ProcessedAt { get; set; }

        /// <summary>
        /// 处理者
        /// </summary>
        public string? ProcessedBy { get; set; }

        /// <summary>
        /// 添加的关联数量
        /// </summary>
        public int AddedAssociationsCount { get; set; }

        /// <summary>
        /// 关联ID列表
        /// </summary>
        public List<Guid> AssociationIds { get; set; } = new List<Guid>();

        /// <summary>
        /// 操作是否成功
        /// </summary>
        public bool IsSuccess => AddedAssociationsCount > 0;
    }



    #endregion
}